# coding:utf-8
# 测试相关工作的计划管理
from __future__ import division
import numpy as np
import json, datetime
from MCaseManage import CasePlan, CasePlanProcess, CaseSubPlan, db,BaseCase,CaseResult
from  httpApi.MHttpApi import ApiCase
from sqlalchemy import not_, and_, or_
from sqlalchemy.sql import func
import UserManage.userBussiness
import caseManage.baseCaseBussiness
import httpApi.apiBussiness


def case_plan_process_manage(content):
    CasePlanProcess(case_plan_id=content['case_plan_id'],
                    case_sub_plan_id=content['case_sub_plan_id'],
                    process=content['process'],
                    note=content['note'],
                    up_person=content['up_person']).add()
    #   如果进度为100%，那么主任务的状态应该为完成状态
    if content['process'] in (100, '100'):
        casePlan_work_sate_complete(content['case_plan_id'], 1)
        #   如果主任务状态为100，则所有子任务的状态也为100
        casePlan_sub_main_process(content['case_plan_id'], content['up_person'])
    else:
        casePlan_work_sate_complete(content['case_plan_id'], 0)
        if content['case_plan_id'] == 0 and content['case_sub_plan_id'] != 0:
            # 子任务更改时，将主任务的状态值进行更改
            subId = content.get('case_sub_plan_id')

            avgProcess, casePlanId = casePlan_main_sub_process(subId)
            processContent = {"case_plan_id": casePlanId, "case_sub_plan_id": 0, "process": avgProcess,
                              "note": "子任务进度变更，主任务自动变更", "up_person": content['up_person']}

            case_plan_process_manage(processContent)
    # return None


def case_plan_process_all(id, t=0):
    query = db.session().query(CasePlanProcess)
    if t in (0, "0"):
        query = query.filter(CasePlanProcess.case_plan_id == id)
    else:
        query = query.filter(CasePlanProcess.case_sub_plan_id == id)
    data = query.all()
    list = []
    for d in data:
        c = d.__dict__
        del (c['_sa_instance_state'])
        list.append(c)
    return list


def case_plan_process_byId(id, t=0):
    query = db.session().query(CasePlanProcess)
    if t in (0, "0"):
        query = query.filter(and_(CasePlanProcess.case_plan_id == id))
    else:
        query = query.filter(and_(CasePlanProcess.case_sub_plan_id == id))

    query = query.order_by(CasePlanProcess.id.desc())
    data = query.first()
    if data:
        return int(data.process)
    return 0


def case_paln_sub_srh(id):
    """根据id查询所有的子任务"""
    query = db.session().query(CaseSubPlan)
    query = query.filter(CaseSubPlan.case_plan_id == id)
    list = []
    for d in query.all():
        c = d.__dict__
        sub_process = case_plan_process_byId(c['id'], t=1)
        del (c['_sa_instance_state'])
        c['sub_process'] = sub_process
        list.append(c)
    return list


def case_plan_sub_delete(id):
    """删除某个子任务"""
    query = CaseSubPlan.query.filter(CaseSubPlan.id == id).first()
    if query:
        db.session.delete(query)
        db.session.commit()
        return id


def case_sub_plan_srh(case_main_id):
    query = db.session().query(CaseSubPlan)
    query = query.filter(CaseSubPlan.case_plan_id == case_main_id)
    #   获取主任务的相关信息
    mainInfo = CasePlan.query.filter(CasePlan.id==case_main_id).first()
    if mainInfo:
        project_id = mainInfo.project_id
        project_version = mainInfo.project_version

    list = []
    for d in query.all():
        c = d.__dict__
        del (c['_sa_instance_state'])

        work_charge_id = c['person']
        work_charge = UserManage.userBussiness.getNameById(work_charge_id)
        c['person_name'] = work_charge
        c['work_content'] = json.loads(c['work_content'])
        if project_id!="" and project_version!="" and c['work_type'] in (1,"1"):
            case_version = c.get('work_content').get('case_plan')
            moudle_list = c.get('work_content').get('case_module')
            # 查询用例模块的进度信息
            taskPrcess = caseManage.baseCaseBussiness.caseResult_byTask(project_id,project_version,case_version,moudle_list)
            c['taskPrcess'] = taskPrcess
        # 查询进度表中的信息
        sub_process = case_plan_process_byId(c['id'], t=1)
        c['sub_process'] = sub_process
        list.append(c)
    return list


def case_plan_srh(project_id, work_state, work_p_start, work_p_end, key_words, page, limit):
    """
    查询测试主干计划的内容
    """
    query = db.session().query(CasePlan)
    if project_id != "":
        query = query.filter(CasePlan.project_id == project_id)
    if work_state != "":
        query = query.filter(CasePlan.work_state == work_state)
    if work_p_start != "":
        query = query.filter(CasePlan.work_p_start >= work_p_start)
    if work_p_end != "":
        query = query.filter(CasePlan.work_p_end <= work_p_end)
    if key_words != "":
        key_words = "%%%s%%" % key_words
        query = query.filter(or_(CasePlan.project_version.like(key_words),
                                 CasePlan.plan_type.like(key_words),
                                 CasePlan.work_type.like(key_words),
                                 CasePlan.work_content.like(key_words),
                                 CasePlan.work_charge.like(key_words),
                                 ))
    count = query.count()
    data = query.paginate(int(page), int(limit), False)
    list = []
    for d in data.items:
        c = d.__dict__
        main_process = case_plan_process_byId(c['id'])
        del (c['_sa_instance_state'])
        #   增加逻辑，如果主任务下面的子任务有用例执行，则读取用例执行的进度并且更新到主任务以及子任务的状态
        work_charge_id = c['work_charge']
        work_charge = UserManage.userBussiness.getNameById(work_charge_id)
        c['work_charge_name'] = work_charge
        c['main_process'] = main_process
        sub_task = case_paln_sub_srh(c['id'])
        if len(sub_task) > 0:
            c['sub_task'] = 1
        list.append(c)
    return list, count


def casePlan_work_sate_complete(id, value=1):
    """如果进度为100%，那么当前任务的状态应该为100%"""
    query = CasePlan.query.filter(CasePlan.id == id).first()
    if query:
        query.work_state = value
        db.session.commit()
        return query.id


def casePlan_sub_manage(content):
    work_content = json.dumps(content['work_content'])
    id = ""
    if content.has_key("id"):
        if content['id'] != "":
            query = CaseSubPlan.query.filter(CaseSubPlan.id == content['id']).first()
            if query:
                c = query.__dict__
                if content.has_key("_sa_instance_state"):
                    del (c['_sa_instance_state'])
                    del (c['update_time'])
                if c == content:
                    return query.id
                query.work_type = content['work_type']
                query.work_content = work_content
                query.p_end = content['p_end']
                query.c_end = content['c_end']
                query.person = content['person']
                query.update_time = str(datetime.datetime.now())
                db.session.commit()
                id = query.id

        else:
            id = CaseSubPlan(content['case_plan_id'], content['work_type'], work_content,
                             content['p_end'], content['c_end'], content['person']).add()
    if content['c_end'] != "":
        processContent = {"case_plan_id": 0, "case_sub_plan_id": id, "process": 100,
                          "note": "子任务完成，进度自动变更", "up_person": content['person']}
        case_plan_process_manage(processContent)
    # 得到所有子项目的进度状态
    avgProcess, casePlanId = casePlan_main_sub_process(id)
    #   更新到主任务的状态中
    processContent = {"case_plan_id": content['case_plan_id'], "case_sub_plan_id": 0,
                      "process": avgProcess,"note": "子任务变动，主任务自动变更", "up_person": content['person']}
    case_plan_process_manage(processContent)

    return id


def casePlan_sub_main_process(id, up_person=""):
    """如果主进度为完成，或者100%，那么所有的子任务的状态也应该为100"""
    query = CaseSubPlan.query.filter(CaseSubPlan.case_plan_id == id).all()
    for d in query:
        processContent = {"case_plan_id": 0, "case_sub_plan_id": d.id, "process": 100,
                          "note": "主任务完成，子任务自动变更", "up_person": up_person}
        case_plan_process_manage(processContent)


def casePlan_getMainID(id):
    query = CaseSubPlan.query.filter(CaseSubPlan.id == id).first()
    if query:
        return query.case_plan_id

def casePlan_main_sub_process(id):
    #   如果子进度变更，则主进程也会根着变更
    #   根据主任务Id，获取所有子任务Id，再根据所有子任务Id获取所有的值
    pQuery = True
    if pQuery:
        mainId = casePlan_getMainID(id)
        if mainId:
            list = []
            sQuery = CaseSubPlan.query.filter(CaseSubPlan.case_plan_id == mainId).all()
            #   得到所有子进度的进度值
            for d in sQuery:
                process = case_plan_process_byId(d.id, t=1)
                list.append(process)
            average_a = np.mean(list)
            #   返回主进度更新为平均值
            return round(average_a, 2), mainId


def casePlan_main_manage(content):
    if content.has_key("id"):
        if content['id'] != "":
            query = CasePlan.query.filter(CasePlan.id == content['id']).first()
            if query:
                c = query.__dict__
                if content.has_key("_sa_instance_state"):
                    del (c['_sa_instance_state'])
                    del (c['update_time'])
                if c == content:
                    return query.id
                processContent = {"case_plan_id": query.id, "case_sub_plan_id": 0, "process": 100,
                                  "note": "工作完成，自动变更", "up_person": content['up_person']}
                if content['work_state'] in (1, "1") or content['work_end'] != "":
                    case_plan_process_manage(processContent)
                    #   所有子进度也应该为100
                    casePlan_sub_main_process(query.id, content['up_person'])

                # oldText = "p_start:%s,p_end:%s"%(query.work_p_start,query.work_p_end)
                # newTest = "p_start:%s,p_end:%s"%(content.get("work_p_start"),content.get("work_p_end"))

                query.project_id = content['project_id']
                query.project_version = content['project_version']
                query.plan_type = content['plan_type']
                query.work_p_start = content['work_p_start']
                query.work_p_end = content['work_p_end']
                query.work_end = content['work_end']
                query.work_state = content['work_state']
                query.work_charge = content['work_charge']
                query.up_person = content['up_person']
                query.update_time = str(datetime.datetime.now())
                db.session.commit()
                return query.id
    id = CasePlan(project_id=content['project_id'], project_version=content['project_version']
                  , plan_type=content['plan_type'], work_p_start=content['work_p_start']
                  , work_p_end=content['work_p_end'], work_end=content['work_end']
                  , work_state=content['work_state'], work_charge=content['work_charge'],
                  up_person=content['up_person']).add()
    return id

def case_sys_total_byme(userId):
    """统计自己名下的各项信息"""
    #我的任务累计总数
    p1 = CasePlan.query.filter(CasePlan.up_person == userId).count()
    p2 = CaseSubPlan.query.filter(CaseSubPlan.person == userId).count()
    total_task = p1 + p2
    # 我未完成的任务数
    cp1 = CasePlan.query.filter(and_(CasePlan.up_person == userId,CasePlan.work_state==0)).count()
    cp2 = CaseSubPlan.query.filter(and_(CaseSubPlan.person == userId,CaseSubPlan.c_end!="")).count()
    total_process_task = cp1+cp2

    #我创建的用例
    c1 = BaseCase.query.filter(BaseCase.in_person == userId).count()


    #我执行的用例
    r1 = CaseResult.query.filter(CaseResult.person==userId).count()
    r2 = CaseResult.query.filter(and_(CaseResult.person == userId,CaseResult.result=='FAIL')).count()

    #我创建的接口数
    a1 = ApiCase.query.filter(ApiCase.person==userId).count()
    if r1:
        caseFailRate = round(r2/r1,2)*100
    else:
        caseFailRate = 0

    return {'crtApi':a1,'total_task':total_task,'total_process_task':total_process_task,'crt_case':c1,'doResult':r1,'failResult':r2,'caseFailRate':caseFailRate}

def case_sys_order():
    """用例缺陷率排名"""
    allUser = UserManage.userBussiness.allUser()
    list = []
    for ur in  allUser:
        r1 = CaseResult.query.filter(CaseResult.person == ur.get('id')).count()
        r2 = CaseResult.query.filter(and_(CaseResult.person == ur.get('id'), CaseResult.result == 'FAIL')).count()
        if r1:
            caseFailRate = round(r2 / r1, 2) * 100
        else:
            caseFailRate = r1
        list.append({'userNameOrder':ur.get('userName'),"dCase":r1,'doCaseFail':r2,'caseFailRate':caseFailRate})
    return list

def case_sys_orderByPjt():
    """所有项目的大概情况"""
    allProject = httpApi.apiBussiness.project_select_all()
    list = []
    for ur in allProject:
        r1 = CaseResult.query.filter(CaseResult.project_id == ur.get('id')).count()
        r2 = CaseResult.query.filter(and_(CaseResult.project_id == ur.get('id'), CaseResult.result == 'FAIL')).count()
        if r1:
            caseFailRate = round(r2 / r1, 2) * 100
        else:
            caseFailRate = r1
        list.append({'projectName': ur.get('project_name'), "dCase": r1, 'doCaseFail': r2, 'caseFailRate': caseFailRate})
    return list
def case_sys_allUserOrder():
    """所有用户的相关数据"""
    allUser = UserManage.userBussiness.allUser()
    list = []
    for ur in allUser:
        data = case_sys_total_byme(ur.get('id'))
        data['userName'] = ur.get('userName')
        list.append(data)
    return list